#include "libxls/WorkBook.h"

WorkBook::WorkBook(const char* path, const char* charset)
{
	m_pWorkBook = xls::xls_open(path, charset);
	m_pWorkSheet = NULL;
	m_nSheetIdx = -1;
	m_nRow = 0;
	m_nCol = 0;
}
WorkBook::~WorkBook()
{
	if (m_pWorkSheet) xls::xls_close_WS(m_pWorkSheet);
	if (m_pWorkBook) xls::xls_close_WB(m_pWorkBook);
}

int WorkBook::SheetCount()
{
	return m_pWorkBook ? m_pWorkBook->sheets.count : 0;
}
const char* WorkBook::SheetName(int nSheetIdx)
{
	if (nSheetIdx < 0 || nSheetIdx >= SheetCount()) return NULL;
	return (const char*)m_pWorkBook->sheets.sheet[nSheetIdx].name;
}

int WorkBook::Row(int nSheetIdx)
{
	Sheet(nSheetIdx);
	return m_nRow;
}
int WorkBook::Col(int nSheetIdx)
{
	Sheet(nSheetIdx);
	return m_nCol;
}

const char* WorkBook::Cell(int nSheetIdx, int nRowIdx, int nColIdx)
{
	xls::xlsWorkSheet* ws = Sheet(nSheetIdx);
	if (ws == NULL) return NULL;
	xls::st_cell_data* cell = &ws->rows.row[nRowIdx].cells.cell[nColIdx];
	return (const char*)cell->str;
}

xls::xlsWorkSheet* WorkBook::Sheet(int nSheetIdx)
{
	if (nSheetIdx < 0 || nSheetIdx >= SheetCount()) return NULL;

	if (nSheetIdx != m_nSheetIdx)
	{
		m_nSheetIdx = nSheetIdx;

		if (m_pWorkSheet) xls::xls_close_WS(m_pWorkSheet);
		m_pWorkSheet = xls::xls_getWorkSheet(m_pWorkBook, m_nSheetIdx);
		xls::xls_parseWorkSheet(m_pWorkSheet);

		m_nRow = 0;
		m_nCol = 0;

		for (int i = 0; i < m_pWorkSheet->rows.lastrow + 1; i++)
		{
			for (int j = 0; j < m_pWorkSheet->rows.lastcol; j++)
			{
				if (m_pWorkSheet->rows.row[i].cells.cell[j].str != NULL)
				{
					if (i + 1 > m_nRow) m_nRow = i + 1;					
					if (j + 1 > m_nCol) m_nCol = j + 1;
				}
			}
		}
	}
	
	return m_pWorkSheet;
}